<?php


/**
 * 下午茶申请单类
 * @package  htdocs 
 * @subpackage  quanliadmin
 * @author   allen.qiang  <allen.qiang@fistforward.com> 2015-01-14 allen.qiang FUN-AC-0028-下午茶项目
 * @version 1.0
 */

class sysApply{


    /**
     * 获取下午茶申请单信息
     * @param $arg_array
     * @return array|null
     */
    public function getApplyList(&$arg_array){
    	global $G_PGLOB;
        //sql字符串
        $sql = '';
        
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //状态
        if (isset($arg_array['status']) && is_numeric($arg_array['status']) ) {
            $sql .= ' AND a.status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['status'];
        }

        //申请编号
        if (isset($arg_array['apply_id']) && !empty($arg_array['apply_id'])) {
            $sql .= ' AND a.apply_id = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['apply_id'];
        }

        //配送日期
        if (isset($arg_array['apply_date']) && !empty($arg_array['apply_date'])) {
            $sql .= ' AND a.apply_date = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['apply_date'];
        }

        //配送城市ID
        if (isset($arg_array['cityID']) && !empty($arg_array['cityID'])) {
            $sql .= ' AND a.cityID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityID'];
        }

        //配送站
        if (isset($arg_array['distribution_id']) && !empty($arg_array['distribution_id'])) {
            $sql .= ' AND a.distribution_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['distribution_id'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM dunch_apply a  ' . $sql;
                $count_array = &$G_PGLOB->DBCA->stmt_query($search_sql, $params_type, $params_array);

                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            $sql=str_replace("WHERE","HAVING",$sql);

            //查询分类信息
            $search_sql = "SELECT a.*,GROUP_CONCAT((CONCAT(b.`product_name`,'：', b.`apply_amount`,'个')) SEPARATOR '，')AS product_detail FROM `dunch_apply` a LEFT JOIN `dunch_apply_detail` b ON a.apply_id=b.apply_id GROUP BY a.apply_id " . $sql;
            $temp_item_array = &$G_PGLOB->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            $item_array = array();

            foreach($temp_item_array as &$item) {
            	
                $item_array[] = array(
                    'creator' => $item->creator,
                    'brandID' => $item->brandID,
                    'apply_id' => $item->apply_id,
                    'status' => $item->status,
                    'apply_date' => $item->apply_date,
                    'distribution_id' => $item->distribution_id,
                    'distribution_name' => $item->distribution_name,
                    'createTime' => $item->createTime,
                    'apply_user_id' => $item->apply_user_id,
                    'apply_user_name' => $item->apply_user_name,
                    'cityID' => $item->cityID,
                    'cityName' => $item->cityName,
                	'total_num' => $item->total_num,
                	'remark' => $item->remark,
                    'product_detail' => $item->product_detail
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 得到入库商品详情
     */
    public function get_dunch_stock_batch($apply_id){
        global $G_PGLOB;
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //申请编号
        if (isset($apply_id) && !empty($apply_id)) {
            $sql .= ' AND apply_id = ?';
            $params_type .= 's';
            $params_array[] = $apply_id;
        }


        if ($sql) {
            $sql = ' HAVING ' . substr($sql, 4) ;
        }

        try {

            //查询分类信息
            $search_sql = "SELECT apply_id,product_code,product_name,SUM(paid_amount) AS paid_amount FROM `dunch_stock_batch` GROUP BY apply_id,product_code,product_name  ".$sql;
            $temp_item_array = &$G_PGLOB->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return "";

            $item_string="";

            foreach($temp_item_array as &$item) {
                $item_string.=$item->product_name."：".$item->paid_amount."个，";
            }

            return $item_string;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return "";

        }

    }

    //添加采购单
    public function addApply(){
        global $G_SHOP;

        //检查参数
        if (!isset($_REQUEST['apply_date'])) {
            return array( 'code' => 400, 'message' => '配送日期不能为空' );
        }

        if (!isset($_REQUEST['cityID'])) {
            return array( 'code' => 400, 'message' => '配送城市不能为空' );
        }

        if (!isset($_REQUEST['distribution_id'])) {
            return array( 'code' => 400, 'message' => '配送站不能为空' );
        }

        if (!isset($_REQUEST['general_goods'])) {
            return array( 'code' => 400, 'message' => '商品信息不能为空' );
        }

        //取值
        $apply_id=$this->getApplyId();
        $brandID=1;
        $custID=$G_SHOP->currentUserID; //后台用户ID
        $custName=$G_SHOP->currentUserName; //后台用户姓名
        $apply_date=$_REQUEST["apply_date"]; //配送日期
        $cityID=$_REQUEST["cityID"]; //城市ID
        $cityName=$_REQUEST["cityName"]; //城市名称
        $distribution_id=$_REQUEST["distribution_id"]; //配送站ID
        $distribution_name=$_REQUEST["distribution_name"]; //配送站名称
        $remark=$_REQUEST["remark"]; //备注
        $total_num=0; //申请总数量
        foreach($_REQUEST['general_goods'] as $v) {
            $total_num+= $v['apply_amount'];
        }

        try{
            $G_SHOP->DBCA->beginTransaction();

            //保存试吃申请表数据
            $dunch_apply = new entity('dunch_apply');
            $dunch_apply->creator = $custID;
            $dunch_apply->apply_id = $apply_id;
            $dunch_apply->apply_date = $apply_date;
            $dunch_apply->apply_user_id =$custID;
            $dunch_apply->apply_user_name = $custName;
            $dunch_apply->cityID = $cityID;
            $dunch_apply->cityName = $cityName;
            $dunch_apply->distribution_id = $distribution_id;
            $dunch_apply->distribution_name = $distribution_name;
            $dunch_apply->brandID = $brandID;
            $dunch_apply->total_num = $total_num;
            $dunch_apply->remark = $remark;
            $dunch_apply->status = 0;
            if (!$G_SHOP->DBCA->save($dunch_apply)) {
                throw new Exception('页面已过期，请刷新页面重试', 404);
            }

            //添加下午茶申请单商品信息
            foreach($_REQUEST['general_goods'] as $key=>$v) {
                //添加采购单商品表数据
                $dunch_apply_detail = new entity('dunch_apply_detail');
                $dunch_apply_detail->creator = $custID;
                $dunch_apply_detail->apply_id = $apply_id;
                $dunch_apply_detail->product_code = $v['product_code'];
                $dunch_apply_detail->product_name =$v['product_name'];
                $dunch_apply_detail->apply_amount = $v['apply_amount'];
                if (!$G_SHOP->DBCA->save($dunch_apply_detail)) {
                    throw new Exception('页面已过期，请刷新页面重试', 404);
                }

                //添加库存表数据
                $dunch_stock = new entity('dunch_stock');
                $dunch_stock->brandID = $brandID;
                $dunch_stock->distribution_id = $distribution_id;
                $dunch_stock->distribution_name = $distribution_name;
                $dunch_stock->stock_date =$apply_date;
                $dunch_stock->product_code = $v['product_code'];
                $dunch_stock->product_name =$v['product_name'];
                if($G_SHOP->DBCA->fetch($dunch_stock)){
                    $dunch_stock->total_apply_amount += $v['apply_amount'];
                }else{
                    $dunch_stock->total_apply_amount = $v['apply_amount'];
                }
                $dunch_stock->creator = $custID;

                if (!$G_SHOP->DBCA->save($dunch_stock)) {
                    throw new Exception('页面已过期，请刷新页面重试', 404);
                }
            }

            $G_SHOP->DBCA->commit();
            return array( 'code' => 200, 'message' => '添加采购单成功！' );
        }
        catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }


    }

    //生成采购单申请编号
    public function getApplyId(){
        global $G_PGLOB;
        $date=date("Y-m-d");
        $date=str_replace("-","",$date);
        $strDate=substr($date,2);
        $applyId=$strDate."001";
        $search_sql = "SELECT MAX(apply_id) AS apply_id  FROM `dunch_apply` WHERE apply_id LIKE '".$strDate."%'";
        $item_array = &$G_PGLOB->DBCA->stmt_query($search_sql);

        if ($item_array && $item_array[0]->apply_id>0)
            return $item_array[0]->apply_id+1;
        else
            return $applyId;
    }

    //生成入库批次编号
    public function getBatchId(){
        global $G_PGLOB;
        $date=date("Y-m-d");
        $strDate=str_replace("-","",$date);
        $batch_id=$strDate."001";
        $search_sql = "SELECT MAX(batch_id) AS batch_id  FROM `dunch_stock_batch` WHERE batch_id LIKE '".$strDate."%'";
        $item_array = &$G_PGLOB->DBCA->stmt_query($search_sql);

        if ($item_array && $item_array[0]->batch_id>0)
            return $item_array[0]->batch_id+1;
        else
            return $batch_id;
    }

    //删除下午茶采购单
    public function delApply(){
        global $G_SHOP;
        //检查参数
        if (!isset($_REQUEST['applyID'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        $applyID=$_REQUEST['applyID'];

        try{
            $G_SHOP->DBCA->beginTransaction();

            for($i=0;$i<count($applyID);$i++){
                $del_sql = "DELETE FROM `dunch_apply` WHERE apply_id='".$applyID[$i]."'";
                $G_SHOP->DBCA->stmt_query($del_sql);
                $del_sql2 ="DELETE FROM `dunch_apply_detail` WHERE apply_id='".$applyID[$i]."'";
                $G_SHOP->DBCA->stmt_query($del_sql2);
            }
            $G_SHOP->DBCA->commit();
            return array( 'code' => 200, 'message' => '删除采购单成功！' );
        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }

    //修改下午茶采购单状态
    public function modApply(){
        global $G_SHOP;
        //检查参数
        if (!isset($_REQUEST['status'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (!isset($_REQUEST['applyID'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        $applyID=$_REQUEST['applyID'];
        $status=$_REQUEST['status'];
        try{
            $G_SHOP->DBCA->beginTransaction();

            //修改状态
            $dunch_apply =  new entity('dunch_apply');
            $dunch_apply->apply_id = $applyID;
            $G_SHOP->DBCA->fetch($dunch_apply);
            $dunch_apply->status = $status;
            $G_SHOP->DBCA->save($dunch_apply);

            if($status==10){ //取消采购单时减去对应库存数量
                //库存申请数量变动
                $dunch_apply = new entity('dunch_apply');
                $dunch_apply->apply_id = $applyID;
                $G_SHOP->DBCA->fetch($dunch_apply);
                $sql = "SELECT * FROM `dunch_apply_detail` WHERE apply_id='".$applyID."'";
                $dunch_apply_detail=$G_SHOP->DBCA->stmt_query($sql);
                foreach($dunch_apply_detail as &$item) {
                    $dunch_stock = new entity('dunch_stock');
                    $dunch_stock->brandID = $dunch_apply->brandID;
                    $dunch_stock->distribution_id = $dunch_apply->distribution_id;
                    $dunch_stock->distribution_name = $dunch_apply->distribution_name;
                    $dunch_stock->stock_date =$dunch_apply->apply_date;;
                    $dunch_stock->product_code =  $item->product_code;
                    $dunch_stock->product_name = $item->product_name;
                    if($G_SHOP->DBCA->fetch($dunch_stock)){
                        $dunch_stock->total_apply_amount -= $item->apply_amount;
                    }
                    if (!$G_SHOP->DBCA->save($dunch_stock)) {
                        throw new Exception('页面已过期，请刷新页面重试', 404);
                    }
                }
            }

            $G_SHOP->DBCA->commit();
            return array( 'code' => 200, 'message' => '修改成功！' );
        }catch (Exception $e) {
            $G_SHOP->DBCA->rollBack();
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }

    //采购单入库
    public function applyWarehousing(){
        global $G_SHOP;

        //取值
        $apply_id=$_REQUEST["applyID"]; //申请编号
        $custID=$G_SHOP->currentUserID; //后台用户ID

        try{
            $G_SHOP->DBCA->beginTransaction();

            //添加入库信息
            foreach($_REQUEST['general_goods'] as $key=>$v) {
                $batch_id=$this->getBatchId(); //入库批次编号
                //添加采购单商品表数据
                $dunch_stock_batch = new entity('dunch_stock_batch');
                $dunch_stock_batch->creator = $custID;
                $dunch_stock_batch->batch_id = $batch_id;
                $dunch_stock_batch->apply_id = $apply_id;
                $dunch_stock_batch->brandID = 1;
                $dunch_stock_batch->product_code = $v['product_code'];
                $dunch_stock_batch->product_name =$v['product_name'];
                $dunch_stock_batch->paid_amount = $v['paid_amount'];
                $dunch_stock_batch->remark= $v['remark'];
                if (!$G_SHOP->DBCA->save($dunch_stock_batch)) {
                    throw new Exception('页面已过期，请刷新页面重试', 404);
                }

                //库存实际数量变动
                $dunch_apply = new entity('dunch_apply');
                $dunch_apply->apply_id = $apply_id;
                $G_SHOP->DBCA->fetch($dunch_apply);
                $dunch_stock = new entity('dunch_stock');
                $dunch_stock->brandID = $dunch_apply->brandID;
                $dunch_stock->distribution_id = $dunch_apply->distribution_id;
                $dunch_stock->distribution_name = $dunch_apply->distribution_name;
                $dunch_stock->stock_date =$dunch_apply->apply_date;;
                $dunch_stock->product_code =  $v['product_code'];
                $dunch_stock->product_name = $v['product_name'];
                if($G_SHOP->DBCA->fetch($dunch_stock)){
                    $dunch_stock->total_paid_amount += $v['paid_amount'];
                }
                if (!$G_SHOP->DBCA->save($dunch_stock)) {
                    throw new Exception('页面已过期，请刷新页面重试', 404);
                }
                $dunch_apply->status = 3; //入库
                $G_SHOP->DBCA->save($dunch_apply);

                //添加入库日志
                $dunch_stock_log = new entity('dunch_stock_log');
                $dunch_stock_log->creator = $custID;
                $dunch_stock_log->stock_id = $dunch_stock->stock_id;
                $dunch_stock_log->log_type = 1; //入库
                $dunch_stock_log->amount = $v['paid_amount'];
                $dunch_stock_log->remark= $v['remark'];
                if (!$G_SHOP->DBCA->save($dunch_stock_log)) {
                    throw new Exception('页面已过期，请刷新页面重试', 404);
                }
            }

            $G_SHOP->DBCA->commit();
            return array( 'code' => 200, 'message' => '入库成功！' );
        }
        catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 700, 'message' => '系统错误' );
            }
        }
    }


}